// 词源服务 - 适配微信小程序环境

/**
 * 从Free Dictionary API获取词源信息
 * @param {string} word - 要查询的单词
 * @returns {Promise<Object>} - 返回词源信息
 */
function fetchEtymologyFromFreeAPI(word) {
  return new Promise((resolve, reject) => {
    // 确保wx对象存在（兼容微信小程序环境）
    if (typeof wx === 'undefined' || !wx.request) {
      reject(new Error('wx对象未定义或wx.request不可用。请在微信小程序环境中使用此服务。'));
      return;
    }
    
    const url = `https://api.dictionaryapi.dev/api/v2/entries/en/${encodeURIComponent(word)}`;
    console.log('Fetching etymology from Free Dictionary API:', url);
    
    wx.request({
      url: url,
      method: 'GET',
      success: (res) => {
        console.log('Free Dictionary API response status:', res.statusCode);
        if (res.statusCode === 200 && res.data && res.data.length > 0) {
          const etymologyInfo = extractEtymologyFromDictionaryAPI(res.data[0]);
          resolve(etymologyInfo);
        } else {
          reject(new Error(`API error! status: ${res.statusCode}`));
        }
      },
      fail: (error) => {
        console.error('获取词源信息失败:', error);
        reject(error);
      }
    });
  });
}

/**
 * 从etymonline获取词源信息（备用方案）
 * @param {string} word - 要查询的单词
 * @returns {Promise<Object>} - 返回词源信息
 */
function fetchEtymology(word) {
  return new Promise((resolve, reject) => {
    // 确保wx对象存在（兼容微信小程序环境）
    if (typeof wx === 'undefined' || !wx.request) {
      reject(new Error('wx对象未定义或wx.request不可用。请在微信小程序环境中使用此服务。'));
      return;
    }
    
    // 尝试直接访问单词页面而不是搜索结果页面
    const url = `https://www.etymonline.com/word/${encodeURIComponent(word)}`;
    console.log('Fetching etymology from URL:', url);
    
    wx.request({
      url: url,
      method: 'GET',
      success: async (res) => {
        console.log('HTTP response status:', res.statusCode);
        if (res.statusCode === 200) {
          const etymologyInfo = extractEtymologyFromHTML(res.data);
          // 请求中文翻译
          await addChineseTranslation(etymologyInfo);
          resolve(etymologyInfo);
        } else {
          reject(new Error(`HTTP error! status: ${res.statusCode}`));
        }
      },
      fail: (error) => {
        console.error('获取词源信息失败:', error);
        reject(error);
      }
    });
  });
}

/**
 * 从Free Dictionary API响应中提取词源信息
 * @param {Object} wordData - Free Dictionary API返回的单词数据
 * @returns {Object} - 词源信息对象
 */
function extractEtymologyFromDictionaryAPI(wordData) {
  try {
    console.log('Extracting etymology from Dictionary API data');
    
    // Free Dictionary API doesn't provide etymology information
    // This API only provides definitions, pronunciations, and examples
    // Return failure so we can fall back to etymonline
    return {
      success: false,
      error: 'Free Dictionary API does not provide etymology information'
    };
    
  } catch (error) {
    console.error('解析Dictionary API数据失败:', error);
    return {
      success: false,
      error: error.message
    };
  }
}

/**
 * 从HTML内容中提取词源信息
 * @param {string} htmlContent - HTML内容
 * @returns {Object} - 词源信息对象
 */
function extractEtymologyFromHTML(htmlContent) {
  try {
    console.log('Extracting etymology from HTML, content length:', htmlContent.length);
    const results = [];
    
    // 尝试多种选择器来查找词源信息
    let sectionCount = 0;
    
    // 查找包含词源信息的section (class包含"prose")
    const proseSectionRegex = /<section[^>]*class="[^"]*prose[^"]*"[^>]*>([\s\S]*?)<\/section>/g;
    let sectionMatch;
    
    while ((sectionMatch = proseSectionRegex.exec(htmlContent)) !== null) {
      sectionCount++;
      const sectionContent = sectionMatch[1];
      const paragraphs = extractParagraphsFromSection(sectionContent);
      
      if (paragraphs.length > 0) {
        results.push({
          type: 'etymology',
          content: paragraphs,
          word: paragraphs[0]?.word,
          property: paragraphs[0]?.property
        });
      }
    }
    
    console.log('Found', sectionCount, 'sections with potential etymology content');
    
    // 查找单词标题
    const words = extractWordTitles(htmlContent);
    
    const vocabularies = extractVocabulariesFromScript(htmlContent);
    console.log('vocabularies:', vocabularies)
    
    return {
      success: true,
      words: words,
      etymologySections: results,
      totalSections: results.length,
      summary: results.length > 0 ? results[0].content[0] : 'No etymology found',
      vocabularies: vocabularies
    };
    
  } catch (error) {
    console.error('解析HTML内容失败:', error);
    return {
      success: false,
      error: error.message
    };
  }
}

/**
 * 从section内容中提取段落
 * @param {string} sectionContent - section内容
 * @returns {Array} - 段落数组，每个元素包含word、property和text字段
 */
function extractParagraphsFromSection(sectionContent) {
  const paragraphs = [];
  
  // 提取单词和属性信息
  let word = '';
  let property = '';
  
  // 查找单词（从hyphens-auto类span中）
  const wordRegex = /<span[^>]*class="[^"]*hyphens-auto[^"]*"[^>]*lang="en"[^>]*>([\s\S]*?)<\/span>/;
  const wordMatch = sectionContent.match(wordRegex);
  if (wordMatch) {
    word = cleanHtmlText(wordMatch[1]);
  }
  
  // 查找属性（从property类span中）
  const propertyRegex = /<span[^>]*class="[^"]*pl-2[^"]*text-battleship-gray[^"]*font-serif[^"]*text-2xl[^"]*mobile:text-xl[^"]*"[^>]*>([\s\S]*?)<\/span>/;
  const propertyMatch = sectionContent.match(propertyRegex);
  if (propertyMatch) {
    property = cleanHtmlText(propertyMatch[1]);
  }
  
  // 提取段落文本（排除包含class="text-foreground/80 text-center"的段落）
  const paragraphRegex = /<p(?![^>]*class="[^"]*text-foreground\/80[^"]*text-center[^"]*")[^>]*>([\s\S]*?)<\/p>/g;
  let paragraphMatch;
  
  while ((paragraphMatch = paragraphRegex.exec(sectionContent)) !== null) {
    const cleanText = cleanHtmlText(paragraphMatch[1]);
    if (cleanText && cleanText.length > 20) {
      if(word) {
        paragraphs.push({
          word: word,
          property: property,
          text: cleanText
        });
      }
    }
  }
  
  // 提取blockquote内容
  const blockquoteRegex = /<blockquote[^>]*>([\s\S]*?)<\/blockquote>/g;
  let blockquoteMatch;
  
  while ((blockquoteMatch = blockquoteRegex.exec(sectionContent)) !== null) {
    const cleanText = cleanHtmlText(blockquoteMatch[1]);
    if (cleanText && cleanText.length > 20) {
      paragraphs.push({
        word: word,
        property: property,
        text: cleanText
      });
    }
  }
  
  return paragraphs;
}

/**
 * 清理HTML文本
 * @param {string} htmlText - HTML文本
 * @returns {string} - 清理后的文本
 */
function cleanHtmlText(htmlText) {
  return htmlText
    .replace(/<[^>]*>/g, '') // 移除所有HTML标签
    .replace(/&[^;]*;/g, ' ') // 替换HTML实体
    .replace(/\s+/g, ' ') // 合并多余空格
    .trim();
}

/**
 * 提取单词标题
 * @param {string} htmlContent - HTML内容
 * @returns {Array} - 单词数组
 */
function extractWordTitles(htmlContent) {
  const words = [];
  
  // 尝试多种选择器来查找单词标题
  const wordSelectors = [
    /<span[^>]*id="etymonline_v_\d+"[^>]*>([\s\S]*?)<\/span>/g,
    // /<h1[^>]*class="[^"]*word[^"]*"[^>]*>([\s\S]*?)<\/h1>/g,
    // /<div[^>]*class="[^"]*word[^"]*"[^>]*>([\s\S]*?)<\/div>/g,
    // /<h2[^>]*>([\s\S]*?)<\/h2>/g
  ];
  
  for (const selector of wordSelectors) {
    let match;
    while ((match = selector.exec(htmlContent)) !== null) {
      const wordContent = match[1];
      const wordText = cleanHtmlText(wordContent);
      if (wordText && wordText.length > 0 && wordText.length < 50) {
        words.push(wordText);
      }
    }
    
    // 如果已经找到单词，就不需要尝试其他选择器
    if (words.length > 0) {
      break;
    }
  }
  
  return words;
}

/**
 * 从script标签中提取vocabularies内容并转换为数组
 * @param {string} htmlContent - HTML内容
 * @returns {Array} - 词汇数组
 */
function extractVocabulariesFromScript(htmlContent) {
  try {
    console.log('Extracting vocabularies from script tags');
    const vocabularies = [];
    
    // 查找包含vocabularies的script标签（包括Next.js的特殊script标签）
    const scriptRegex = /<script[^>]*>([\s\S]*?)<\/script>/g;
    let scriptMatch;
    
    while ((scriptMatch = scriptRegex.exec(htmlContent)) !== null) {
      const scriptContent = scriptMatch[1];
      
      // 检查script内容是否包含vocabularies
      if (!scriptContent.includes('vocabularies')) {
        continue;
      }
      
      // 查找vocabularies变量或对象（支持更复杂的嵌套结构）
      const vocabulariesRegex = /vocabularies\s*:\s*([\[\{][\s\S]*?[\]\}])/;
      let vocabulariesMatch = scriptContent.match(vocabulariesRegex);
      
      // 如果还是找不到，尝试在更大的范围内查找vocabularies数组
      if (!vocabulariesMatch && scriptContent.includes('vocabularies')) {
        // 从vocabularies位置开始，手动查找完整的数组结构
        const vocabulariesIndex = scriptContent.indexOf('vocabularies');
        if (vocabulariesIndex !== -1) {
          // 从vocabularies位置开始，向后找到匹配的[...]结构
          let braceCount = 0;
          let inString = false;
          let escapeNext = false;
          let arrayStart = -1;
          
          for (let i = vocabulariesIndex; i < scriptContent.length; i++) {
            const char = scriptContent[i];
            
            if (escapeNext) {
              escapeNext = false;
              continue;
            }
            
            if (char === '\\') {
              escapeNext = true;
              continue;
            }
            
            if (char === '"') {
              inString = !inString;
              continue;
            }
            
            if (!inString) {
              if (char === '[') {
                if (arrayStart === -1) arrayStart = i;
                braceCount++;
              } else if (char === ']') {
                braceCount--;
                if (braceCount === 0 && arrayStart !== -1) {
                  // 找到了完整的数组
                  const arrayContent = scriptContent.substring(arrayStart, i + 1);
                  vocabulariesMatch = [arrayContent];
                  console.log(`Found complete vocabularies array with ${arrayContent.length} characters`);
                  break;
                }
              }
            }
          }
        }
      }
      
      if (vocabulariesMatch) {
        try {
          // 获取JSON内容 - vocabulariesMatch可能是[完整匹配, 捕获组]或只是[内容]
          let jsonContent;
          if (vocabulariesMatch.length > 1 && vocabulariesMatch[1]) {
            jsonContent = vocabulariesMatch[1];
          } else {
            jsonContent = vocabulariesMatch[0];
          }
          
          console.log('Attempting to parse JSON content, length:', jsonContent.length);
          console.log('First 100 chars:', jsonContent.substring(0, 100));
          
          // 解析JSON数据 - 逐步解除转义：先处理四重反斜杠，再处理双重反斜杠，最后处理转义引号
          const cleanedJson = jsonContent
            .replace(/\\\\/g, '\\')  // 四重反斜杠 -> 双重反斜杠
            .replace(/\\\"/g, '"');   // 转义引号 -> 普通引号
          
          console.log('Cleaned JSON first 100 chars:', cleanedJson.substring(0, 100));
          
          const vocabulariesData = JSON.parse(cleanedJson);
          
          if (Array.isArray(vocabulariesData)) {
            // 如果是数组，直接添加
            vocabularies.push(...vocabulariesData);
          } else if (typeof vocabulariesData === 'object') {
            // 如果是对象，提取值或根据结构处理
            if (vocabulariesData.words && Array.isArray(vocabulariesData.words)) {
              vocabularies.push(...vocabulariesData.words);
            } else if (vocabulariesData.vocabulary && Array.isArray(vocabulariesData.vocabulary)) {
              vocabularies.push(...vocabulariesData.vocabulary);
            } else {
              // 提取对象的所有值
              const values = Object.values(vocabulariesData);
              vocabularies.push(...values);
            }
          }
          
          console.log(`Found ${vocabularies.length} vocabularies in script tag`);
          
        } catch (jsonError) {
          console.error('Failed to parse vocabularies JSON:', jsonError);
        }
      }
    }
    return vocabularies;
    
  } catch (error) {
    console.error('提取script标签中的vocabularies失败:', error);
    return [];
  }
}

/**
 * 为词源信息添加中文翻译
 * @param {Object} etymologyInfo - 词源信息对象
 * @returns {Promise<void>}
 */
async function addChineseTranslation(etymologyInfo) {
  try {
    if (!etymologyInfo.vocabularies || !etymologyInfo.etymologySections || 
        etymologyInfo.vocabularies.length === 0 || etymologyInfo.etymologySections.length === 0) {
      console.log('No vocabularies or etymology sections found for translation');
      return;
    }

    console.log('Adding Chinese translation, vocabularies count:', etymologyInfo.vocabularies.length);
    console.log('Etymology sections count:', etymologyInfo.etymologySections.length);

    // 遍历每个etymologySection
    for (let section of etymologyInfo.etymologySections) {
      if (!section.content || section.content.length === 0) continue;

      // 在vocabularies中查找匹配的项
      const matchedVocabulary = etymologyInfo.vocabularies.find(vocab => {
        return vocab.word === section.word && vocab.property === section.property;
      });

      if (matchedVocabulary && matchedVocabulary.domain_id) {
        try {
          // 获取中文翻译
          const translation = await fetchChineseTranslation(matchedVocabulary.domain_id);
          if (translation) {
            console.log('translation:', translation);
            section.translation = translation;
          }
        } catch (translationError) {
          console.error(`Failed to get translation for ${section.word}:`, translationError);
        }
      } else {
        console.log(`No matching vocabulary found for ${section.word} (${section.property})`);
      }
    }
  } catch (error) {
    console.error('添加中文翻译失败:', error);
  }
}

/**
 * 从etymonline API获取中文翻译
 * @param {number} domainId - domain_id
 * @returns {Promise<string>} - 中文翻译文本
 */
async function fetchChineseTranslation(domainId) {
  return new Promise((resolve, reject) => {
    if (typeof wx === 'undefined' || !wx.request) {
      reject(new Error('wx对象未定义或wx.request不可用'));
      return;
    }

    const url = `https://www.etymonline.com/app/api/anon/translation/v2?id=${domainId}&lang=zh-CN`;
    console.log('Fetching Chinese translation from:', url);

    wx.request({
      url: url,
      method: 'GET',
      success: (res) => {
        console.log('Translation API response status:', res.statusCode);
        if (res.statusCode === 200 && res.data) {
          // 解析翻译响应
          if (res.data.data.translation) {
            resolve(cleanHtmlText(res.data.data.translation));
          } else {
            console.log('Unexpected translation response format:', res.data);
            resolve(null);
          }
        } else {
          console.log('Translation API error, status:', res.statusCode);
          resolve(null);
        }
      },
      fail: (error) => {
        console.error('获取中文翻译失败:', error);
        resolve(null);
      }
    });
  });
}

/**
 * 获取简化版词源信息（适合显示）
 * @param {string} word - 要查询的单词
 * @returns {Promise<Object>} - 简化版词源信息
 */
async function getSimpleEtymology(word) {

  // 如果Free Dictionary API失败，尝试etymonline
  try {
    const etymologyData = await fetchEtymology(word);
    console.log('Raw etymology data from etymonline:', etymologyData);
    
    if (etymologyData.success && etymologyData.etymologySections.length > 0) {
      // 获取第一个词源部分的第一个段落作为摘要
      const firstParagraph = etymologyData.etymologySections[0].content[0];
      
      // 截取前200个字符作为简短描述
      const shortDescription = firstParagraph.length > 200 
        ? firstParagraph.substring(0, 200) + '...'
        : firstParagraph;
      
      return {
        success: true,
        word: word,
        shortDescription: shortDescription,
        fullDescription: firstParagraph,
        totalSections: etymologyData.totalSections,
        etymologySections: etymologyData.etymologySections,
        source: 'etymonline'
      };
    } else {
      console.log('No etymology sections found from etymonline. Data:', etymologyData);
    }
  } catch (etymonlineError) {
    console.error('etymonline scraping failed:', etymonlineError);
  }
  
  // 如果所有方法都失败，返回错误
  return {
    success: false,
    error: 'No etymology information found'
  };
}

module.exports = {
  fetchEtymology,
  fetchEtymologyFromFreeAPI,
  extractEtymologyFromHTML,
  extractEtymologyFromDictionaryAPI,
  getSimpleEtymology,
  extractVocabulariesFromScript,
  extractParagraphsFromSection,
  addChineseTranslation,
  fetchChineseTranslation
};